import _ from 'lodash'
import axios, { AxiosRequestConfig } from 'axios'
import { udConfigProvider } from '@/lib'
import { http as baseHttp } from '@/lib'

const httpFactory = {
  create: (config?: AxiosRequestConfig) => {
    const http = axios.create(config)

    http.interceptors.request.use((value: any) => {
      value = _.extend({}, udConfigProvider.http, value)
      if (value.url.indexOf('http') == 0) {
        value.baseURL = ''
      }
      const headers = value.headers
      value = value.requestBeforeSetToken(value)
      value.headers = { ...value.headers, ...headers }
      if (value.useRpcWrap) {
        value.headers['x-rpc-wrap'] = '1'
      }
      value = value.requestBefore(value)
      return value
    }, error => {
      let func = _.get(error, 'config.errorHandler.request', udConfigProvider.http.errorHandler.request)
      func(error)
      return Promise.reject(error)
    })

    http.interceptors.response.use((res: any) => {
      if (res.status === 200) {
        if (res.config.useRpcWrap) {
          if (res.data.code == 0 || res.data.msg == 'ok') {
            res.originalData = res.payload
            res.data = res.data.payload
            return Promise.resolve(res)
          } else {
            if (_.isFunction(res.config.errorHandler[res.data.code])) {
              res.config.errorHandler[res.data.code](res)
            } else {
              if (res.config.useBizErrorHandler) {
                res.config.errorTip({ description: res.data.msg })
              }
            }
            return Promise.reject(res)
          }
        }
        return Promise.resolve(res)
      } else {
  
        res.config.errorTip({ description: res.statusText })
      }
      return Promise.reject(res)
    }, error => {

      console.log(error, error.response)
      if (error.config && error.config.useSysErrorHandler) {
        let handler = error.config.errorHandler.other
        if (error.response) {
          if (_.isFunction(error.config.errorHandler[error.response.status])) {
            handler = error.config.errorHandler[error.response.status]
          }
        }
        handler(error)
      }
      return Promise.reject(error)
    })

    return http
  }
}

/** ajax 请求对象 */
const http = httpFactory.create({ ...baseHttp.defaults })

export { http, httpFactory }
